﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;
using Newtonsoft.Json;
using System.IO;
using System.Diagnostics;
using System.Threading;

namespace ChangeIP
{
    public partial class ChangeIPForm : Form
    {
        public InternetModel internetModel = new InternetModel();
        public List<InternetModel> internetModelsl = new List<InternetModel>();
        public string configPath = System.Environment.CurrentDirectory + "\\config\\config.json";
        public ChangeIPForm()
        {
            InitializeComponent();
           
        }
        private void save(object sender, EventArgs e)
        {
            if (cb_templatename.Text == null || cb_templatename.Text.Length == 0)
            {
                MessageBox.Show("请先选择一个已存在的模板或者输入一个新的模板名字");

                return;
            }

            if (internetModel == null)
            {
                internetModel = new InternetModel();
            }
            if (cb_DHCP.Checked == true)
            {
                internetModel.isdhcp = true;
            }
            else
            {
                internetModel.isdhcp = false;
            }

            internetModel.ip = tb_ip.Text;
            internetModel.mask= tb_mask.Text;
            internetModel.gateway = tb_gateway.Text;
            internetModel.defultdns =tb_defultdns.Text;
            internetModel.subdns = tb_subdns.Text ;
            string _name = cb_templatename.Text; 
            internetModel.templatename = cb_templatename.Text;

            if (internetModelsl.Where(a=>a.templatename == internetModel.templatename).ToList().Count()>0)
            {
                for (int i = 0; i < internetModelsl.Count; i++)
                {
                    if (internetModelsl[i].templatename == internetModel.templatename)
                    {
                        internetModelsl.RemoveAt(i);
                        break;
                    }
                }
               

            }
            internetModelsl.Add(internetModel);

            string jsonvalue = JsonConvert.SerializeObject(internetModelsl);

            System.IO.File.WriteAllText(configPath, jsonvalue, Encoding.UTF8);



            ChangeIPForm_Load(null,null);
            cb_templatename.Text = _name;

        }
        private void cb_DHCP_CheckedChanged(object sender, EventArgs e)
        {
            if (cb_DHCP.Checked == true)
            {
                tb_ip.Enabled = false;
                tb_mask.Enabled = false;
                tb_gateway.Enabled = false;
                tb_defultdns.Enabled = false;
                tb_subdns.Enabled = false;
            }
            else
            {
                tb_ip.Enabled = true;
                tb_mask.Enabled = true;
                tb_gateway.Enabled = true;
                tb_defultdns.Enabled = true;
                tb_subdns.Enabled = true;
            }

        }

        public bool firstload = true;
        private void ChangeIPForm_Load(object sender, EventArgs e)
        {
            if (firstload)
            {
                cb_network.Items.Clear();
                ManagementClass vNetworkAdapter = new ManagementClass("Win32_NetworkAdapter");
                ManagementObjectCollection vNetworkAdapters = vNetworkAdapter.GetInstances();
                foreach (ManagementObject vNetworkAdapterInfo in vNetworkAdapters)
                {
                    if (vNetworkAdapterInfo.Properties["NetConnectionID"].Value != null)
                    {
                        cb_network.Items.Add(vNetworkAdapterInfo.Properties["NetConnectionID"].Value);
                        //Console.WriteLine("NetConnectionID：{0}", vNetworkAdapterInfo.Properties["NetConnectionID"].Value);
                        //Console.WriteLine("Caption：{0}", vNetworkAdapterInfo.Properties["Caption"].Value);
                        //Console.WriteLine("Description：{0}", vNetworkAdapterInfo.Properties["Description"].Value);
                    }

                }
                if (cb_network.Items.Count > 0)
                {
                    cb_network.Text = cb_network.Items[0].ToString();
                }
                firstload = false;
            }
            if (!File.Exists(configPath))
            {
                FileInfo info = new FileInfo(configPath);
                if (!Directory.Exists(info.DirectoryName))
                {
                    Directory.CreateDirectory(info.DirectoryName);
                }
                System.IO.File.WriteAllText(configPath, "[{\"templatename\":\"default\",\"isdhcp\":true,\"ip\":\"192.168.1.2\",\"mask\":\"255.255.255.0\",\"gateway\":\"192.168.1.1\",\"gwmetric\":null,\"defultdns\":\"\",\"subdns\":\"\"}]", Encoding.UTF8);
            }



            StreamReader srReadFile = new StreamReader(configPath);
            StringBuilder stringBuilder = new StringBuilder();

            while (!srReadFile.EndOfStream)
            {
                string strReadLine = srReadFile.ReadLine(); //读取每行数据
                stringBuilder.AppendLine(strReadLine);

            }

            srReadFile.Close();
            internetModelsl = JsonConvert.DeserializeObject<List<InternetModel>>(stringBuilder.ToString());
            cb_templatename.Items.Clear();
            foreach (var item in internetModelsl)
            {
                cb_templatename.Items.Add(item.templatename);
            }
            if (cb_templatename.Items.Count>0)
            {
                cb_templatename.Text = cb_templatename.Items[0].ToString();
            }
        }

        private void cb_templatename_TextChanged(object sender, EventArgs e)
        {
            internetModel = internetModelsl.Where(item => item.templatename == cb_templatename.Text).FirstOrDefault();

            if (internetModel == null)
            {
                internetModel = new InternetModel();
                return;
            }
            if (internetModel.isdhcp == true)
            {
                cb_DHCP.Checked = true;
            }
            else
            {
                cb_DHCP.Checked = false;
            }
            
            tb_ip.Text = internetModel.ip;
            tb_mask.Text = internetModel.mask;
            tb_gateway.Text = internetModel.gateway;
            tb_defultdns.Text = internetModel.defultdns;
            tb_subdns.Text = internetModel.subdns;

        }

        private void ChangeIPForm_Shown(object sender, EventArgs e)
        {
            //cb_DHCP.CheckedChanged += save;
            //tb_ip.LostFocus += save;
            //tb_mask.LostFocus += save;
            //tb_gateway.LostFocus += save;
            //tb_defultdns.LostFocus += save;
            //tb_subdns.LostFocus += save;
        }

        private void b_Save_Click(object sender, EventArgs e)
        {
            save(sender,e);
            MessageBox.Show($"模板{cb_templatename.Text}已保存");
        }

        private void b_Change_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否要修改"+cb_network.Text+"的网络","请确认",MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }
            save(null, null);

            if (internetModel == null)
            {
                MessageBox.Show("模板为空");
                return;
            }
            string batpath = System.Environment.CurrentDirectory +"\\config\\"+ DateTime.Now.ToString("yyyyMMddHHm0.0mssfff")+ ".bat";
            FileInfo fileInfo = new FileInfo(batpath);

            if (!Directory.Exists(fileInfo.DirectoryName))
            {
                Directory.CreateDirectory(fileInfo.DirectoryName);
            }
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendFormat($"@echo off " + "\r\n");
            stringBuilder.AppendFormat($"cls " + "\r\n");
            stringBuilder.AppendFormat($"color 0A " + "\r\n");
            stringBuilder.AppendFormat($"Echo ******************************************************************************* " + "\r\n");
            stringBuilder.AppendFormat($"Echo           changing IPaddress and DNSserviceaddress,pls wait ...... " + "\r\n");
            stringBuilder.AppendFormat($"Echo ******************************************************************************* " + "\r\n");
            if (internetModel.isdhcp)
            {
                //dhcp
                stringBuilder.AppendFormat($"cmd /c netsh interface ip set address name=\"{cb_network.Text}\" source=dhcp" + "\r\n");
                stringBuilder.AppendFormat($"cmd /c netsh interface ip set dns name=\"{cb_network.Text}\" source=dhcp" + "\r\n");

            }
            else
            {
                //static
                stringBuilder.AppendFormat($"cmd /c netsh interface ip set address name=\"{cb_network.Text}\" source=static addr={internetModel.ip} mask={internetModel.mask} gateway={internetModel.gateway} gwmetric=1 " + "\r\n");
                stringBuilder.AppendFormat($"cmd /c netsh interface ip set dns name=\"{cb_network.Text}\" source=static addr={internetModel.defultdns} " + "\r\n");
                stringBuilder.AppendFormat($"cmd /c netsh interface ip add dns name=\"{cb_network.Text}\" addr={internetModel.subdns} index=2 " + "\r\n");
            }
            stringBuilder.AppendFormat($"ipconfig /all " + "\r\n");
            stringBuilder.AppendFormat($"Echo ******************************************************************************* " + "\r\n");
            stringBuilder.AppendFormat($"Echo          OK! ! done success! !pls press any key ...... " + "\r\n");
            stringBuilder.AppendFormat($"Echo          thx for using " + "\r\n");
            stringBuilder.AppendFormat($"Echo ******************************************************************************* " + "\r\n");
            stringBuilder.AppendFormat($"Pause " + "\r\n");

            System.IO.File.WriteAllText(batpath, stringBuilder.ToString(), Encoding.UTF8);
            ProcessStartInfo start = new ProcessStartInfo(batpath);
            Process.Start(start);
            Thread.Sleep(3_000);
            File.Delete(batpath);
        }

        private void b_deletetemplate_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("是否要删除" + cb_templatename.Text + "模板", "请确认", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }
                if (internetModelsl.Where(a => a.templatename == cb_templatename.Text.ToString()).ToList().Count() > 0)
                {
                    for (int i = 0; i < internetModelsl.Count(); i++)
                    {
                        if (internetModelsl[i].templatename == cb_templatename.Text.ToString())
                        {
                            internetModelsl.RemoveAt(i);
                        }
                    }
                }
                if (internetModelsl.Count() > 0)
                {
                    cb_templatename.Text = internetModelsl[0].templatename;
                }
                cb_templatename.Items.Clear();
                foreach (var item in internetModelsl)
                {
                    cb_templatename.Items.Add(item.templatename);

                }

                save(null,null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("模板删除失败：" + ex);
            }
           
        }
    }
}
